package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright: Copyright (c) 2019 Super520
 * 描述：
 *
 * @package: cn.wolfcode.trip.admin.controller
 * @author: Patch
 * @date: 2019/5/19 15:40
 * 总结:
 */
@Controller
@RequestMapping("region")
public class RegionController {
    @Autowired
    private IRegionService regionService;

    @RequestMapping("list")
    public String list(Model model) {
        model.addAttribute("pageInfo", regionService.listAll(null));
        return "region/list";
    }

    /**
     * @param parentId
     * @param type     通过判断是否有这个值返回前台所需对应的JSON数据
     * @return
     */
    @RequestMapping("listByParentId")
    @ResponseBody
    public List listByParentId(Long parentId, String type) {
        // 查询所有的地区
        List<Region> regions = regionService.listByParentId(parentId);
        // 根据标记返回前端需要的数据
        if ("tree".equals(type)) {
            ArrayList<Map> list = new ArrayList<>();
            // 把每个地区对象转成map，添加前端插件需要的属性
            for (Region region : regions) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id", region.getId());
                map.put("text", region.getName());
                map.put("lazyLoad", true);
                // 判断是否是推荐
                if (region.getState() == Region.STATE_HOT) {
                    map.put("tags", new String[]{"推荐"});
                }
                list.add(map);
            }
            return list;
        } else {
            return regions;
        }
    }

    /**
     * 保存和更新
     *
     * @param region
     * @return
     */
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Region region) {
        JsonResult result = new JsonResult();
        try {
            regionService.saveOrUpdate(region);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("亲，操作失败");
        }
        return result;
    }

    /**
     * 更新状态
     *
     * @param id
     * @param state
     * @return
     */
    @RequestMapping("updateState")
    @ResponseBody
    public Object updateState(Long id, int state) {
        JsonResult result = new JsonResult();
        try {
            regionService.updateState(id, state);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("亲，操作失败");
        }
        return result;
    }
}
